﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Innova.Microfinanzas.BusinessEntities;
using System.Text.RegularExpressions;

namespace MyCommerce.Business.GeneralParameters
{
    public class CustomerManager
    {
        private MyCommerceEntities vContext;

        public CustomerManager()
        {
            if (vContext == null)
            {
                vContext = new MyCommerceEntities();
                vContext.ContextOptions.LazyLoadingEnabled = false;
            }
        }

        public CustomerManager(bool lazyLoad)
        {
            if (vContext == null)
            {
                vContext = new MyCommerceEntities();
                vContext.ContextOptions.LazyLoadingEnabled = lazyLoad;
            }
        }

        public Customer GetCustomerById(long idCustomer)
        {
            var objFindResult = (from c in vContext.Customer
                                 where c.IdCustomer == idCustomer
                                 select c).FirstOrDefault();
            return objFindResult;
        }

        public List<Customer> FindCustomerByNameOrIdentityCard(string searchCriteria)
        {
            var colFindResult = (from c in vContext.Customer
                                 where c.FullName.Contains(searchCriteria)
                                 || c.IdentityCardNumber.Contains(searchCriteria)
                                 select c);
            return colFindResult.ToList();
        }

        public long CreateUpdateCustomer(Customer objCustomer)
        {
            long result = objCustomer.IdCustomer;
            if (objCustomer.IdCustomer == 0)
            {
                vContext.AddToCustomer(objCustomer);                
            }
            else
            {
                Customer objFind = GetCustomerById(result);
                if (objFind != null)
                {
                    objFind.Address = objCustomer.Address;
                    objFind.FullName = objCustomer.FullName;
                    objFind.IdentityCardNumber = objCustomer.IdentityCardNumber;
                    objFind.PhoneNumber = objCustomer.PhoneNumber;
                }
            }
            vContext.SaveChanges();
            result = objCustomer.IdCustomer;
            return result;
        }
    }
}
